#!/usr/bin/python3

import socket
import json

from Drive import Drive

# udp socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 监听1392端口
udp_socket.bind(('0.0.0.0', 1392))

if __name__ == '__main__':
    drive = Drive()
    try:
        while True:
            # 接受数据，最大4k字节
            data, address = udp_socket.recvfrom(4096)
            # 解码并解析为json
            message = json.loads(data.decode('utf8'))
            # 判断指令
            if message['instruction'] == 'MOVE':
                # 运动指令
                # 获取速度
                speed = float(message['content']['speed'])
                # 获取方向
                direction = float(message['content']['direction'])
                # 在终端输出指令
                print(f"move {message['content']['direction']} {message['content']['speed']}")
                # 执行指令
                drive.move(direction, speed)
            elif message['instruction'] == 'STOP':
                drive.stop()
                print('STOP')
    finally:
        # 释放端口
        udp_socket.close()
